﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using System.Threading;

namespace Dotsad.WFField
{
    public partial class StatusFieldEditor : UserControl, IFieldEditor
    {
        public bool DisplayAsNewSection
        {
            get { return false; }
        }

        public void InitializeWithField(Microsoft.SharePoint.SPField field)
        {
            if (!IsPostBack)
            {
                // Fill the workflows intially
                FillWorkflowDropDown();

                //In this method we will sync the custom settings of the field with 
                //our custom setting controls on the editor screen. Field however will be null when we are in create mode, in
                //which case the default value (as specified in the fldtypes XML will apply).
                if (!Page.IsPostBack && field != null)
                {
                    dropDownListLookupWorkflows.SelectedValue = (string)field.GetCustomProperty("WorkFlowProp");
                    chkRenderJava.Checked = (bool)field.GetCustomProperty("WorkFlowAjax");
                }
            }
        }



        //Fill drop down box with avaliable workflows for the selected list.
        private void FillWorkflowDropDown()
        {
            SPList list = SPContext.Current.List;

            if (list.WorkflowAssociations.Count > 0)
            {
                foreach (SPWorkflowAssociation item in list.WorkflowAssociations)
                {
                    dropDownListLookupWorkflows.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                }
            }
            else
            {
                panelEditor.Visible = false;
                panelError.Visible = true;
                labelError.Text = "No Workflow Associations exist, add atleast one workflow to the current list!";
            }
        }


        public void OnSaveChange(Microsoft.SharePoint.SPField field, bool isNewField)
        {
            /*This is perhaps the most tricky part in implementing custom field type properties. 
             * The field param passed in to this method is a different object instance to the actual field being edited.
             * This is why we'll need to set the value to be saved into the LocalThreadStorage, and retrieve it back out
             * in the FieldType class and update the field with the custom setting properties. For more info see
             * http://msdn.microsoft.com/en-us/library/cc889345(office.12).aspx#CreatingWSS3CustomFields_StoringFieldSetting */

            //TODO: Handle case where location is not specified or not valid

            Guid guid = new Guid(dropDownListLookupWorkflows.SelectedValue.ToString());

            SPWorkflowAssociation ss = field.ParentList.WorkflowAssociations[guid];


            /*The status value is stored in a field of type SPFieldWorkflowStatus. Generally this field has the same display 
            * name as your workflow although it’s internal name will be different. Getting the internal name is a pain, 
            * for some bizarre reason Microsoft decided to expose this as an internal property rather than public. 
            * (See SPWorkflowAssociation.InternalNameStatusField). After tracing this back to source via Reflector, 
            * it transpires that this comes from the database and is never exposed as a public property. The best 
            * way I’ve found to locate the correct field is to iterate through them and find one with a title that 
            * matches the workflow name.
            * http://www.chaholl.com/archive/2009/10/03/howto-read-workflow-status-text.aspx */


            string wfStaticName = string.Empty;

            //loop through the fields
            foreach (SPField item in field.ParentList.Fields)
            {
                //If field is a workflow status column
                if (item is SPFieldWorkflowStatus)
                {
                    SPFieldWorkflowStatus statusField = (SPFieldWorkflowStatus)item;

                    //This may not always be true although I've never found a situation where it isn't!
                    if (statusField.Title == dropDownListLookupWorkflows.SelectedItem.ToString())
                    {
                        wfStaticName = statusField.StaticName;
                    }
                }
            }

            Thread.SetData(Thread.GetNamedDataSlot("WorkFlowStaticName"), wfStaticName);
            Thread.SetData(Thread.GetNamedDataSlot("WorkFlowProp"), dropDownListLookupWorkflows.SelectedValue);
            Thread.SetData(Thread.GetNamedDataSlot("WorkFlowAjax"), chkRenderJava.Checked);
        }
    }
}
